package com.nanfang51g3.ckz.ui.fragment.home;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.nanfang51g3.ckz.R;
import com.nanfang51g3.ckz.application.CkzApplication;
import com.nanfang51g3.ckz.event.AvatarEvent;
import com.nanfang51g3.ckz.event.RxBus;
import com.nanfang51g3.ckz.ui.base.IPresenter;
import com.nanfang51g3.ckz.ui.fragment.base.BaseLazyLoadFragment;
import com.nanfang51g3.ckz.ui.home.DaggerHomeMainContractComponent;
import com.nanfang51g3.ckz.ui.home.HomeMainContract;
import com.nanfang51g3.ckz.ui.home.HomeMainPresenter;
import com.nanfang51g3.ckz.ui.home.HomeMainPresenterModule;
import com.nanfang51g3.ckz.ui.money.fill.FillInActivity;
import com.nanfang51g3.ckz.ui.person.PersonActivity;
import com.nanfang51g3.ckz.ui.update.password.UpPasswordActivity;
import com.nanfang51g3.ckz.ui.webView.PublicWebView;
import com.nanfang51g3.ckz.utils.EasyToast;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.SPUtil;
import com.nanfang51g3.ckz.utils.ToolUtils;
import com.nanfang51g3.ckz.widget.GlideCircleTransform;
import com.nanfang51g3.ckz.widget.progress.NumberProgressBar;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by Administrator on 2016/5/18.
 */
public class HomeMeFragment extends BaseLazyLoadFragment implements HomeMainContract.View {
    HomeMainContract.HomeMainActionsListener homeMainActionsListener;
    String url = "http://ckt.51g3.com/aboutapp.html";
    @Bind(R.id.me_iv_avatar)
    ImageView meIvAvatar;
    @Bind(R.id.tv_me_name)
    TextView tvMeName;
    @Bind(R.id.tv_me_phone)
    TextView tvMePhone;
    @Bind(R.id.tv_me_version)
    TextView tvMeVersion;
    @Bind(R.id.home_tv_title)
    TextView homeTvTitle;
    String versionName;
    String versionCode;
    int displayWidth = 0;
    int displayHeight = 0;
    NumberProgressBar numberProgressBar;
    UpdateProgressBarDialog updateProgressBarDialog;
    TextView tv_dialog_version;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //1.
        super.onCreate(savedInstanceState);
        KLog.e("TAG", "onCreate=I");
    }

    @Override
    public IPresenter getPresenter() {
        return homeMainActionsListener;
    }

    @Override
    public void onResume() {
        super.onResume();
        homeTvTitle.setText(getResources().getString(R.string.str_me));
        String username = (String) SPUtil.get(getActivity(), "username", "请填写昵称");
        KLog.i("Evd", "usernmae=" + username + "-" + ToolUtils.isZN(username));
        String cont = "cKTcKT_";
        if (username.contains(cont)) {
            tvMeName.setText("请填写昵称");
        } else {
            tvMeName.setText(username);
        }
        String phone = (String) SPUtil.get(getActivity(), "phone", "暂未填写手机");
        tvMePhone.setText(phone);
        versionName = (String) SPUtil.get(getActivity(), "version_name", "1.0");
        versionCode = (String) SPUtil.get(getActivity(), "version_code", "1");
        tvMeVersion.setText(versionName);
    }

    Subscription rxSubscription;
    //标志位，标志已经初始化完成。
    private boolean isPrepared;

    @Override
    protected void lazyLoad() {
        if (!isPrepared && !isVisible) {
            return;
        }
        //网络请求加载....
        KLog.e("TAG", "lazyLoad-if-I");
    }

    private void initMetrics() {
        // TODO Auto-generated method stub
        DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        // 初始化屏幕宽度
        displayWidth = metric.widthPixels;
        // 初始化屏幕高度
        displayHeight = metric.heightPixels;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_me_fragment, container, false);
        ButterKnife.bind(this, view);
        initMetrics();
        String userPic = (String) SPUtil.get(getActivity(), "userpic", "");
        Glide.with(getActivity()).load(userPic).placeholder(R.mipmap.ic_default_avatar).transform(
                new GlideCircleTransform(getActivity())
        ).into(meIvAvatar);
        homeMainActionsListener = DaggerHomeMainContractComponent
                .builder()
                .appComponent(CkzApplication.getAppComponent())
                .homeMainPresenterModule(new HomeMainPresenterModule(this))
                .build().getHomeMainPresenter();
        rxSubscription = RxBus
                .getDefault()
                .toObservable(AvatarEvent.class)
                .subscribe(new Action1<AvatarEvent>() {
                    @Override
                    public void call(AvatarEvent file) {
                        KLog.i("Evd", "call - AvatarEvent" + file.getUrlAvatar());
                        Glide.with(getActivity()).load(file.getUrlAvatar()).placeholder(R.mipmap.ic_default_avatar).transform(
                                new GlideCircleTransform(getActivity())
                        ).into(meIvAvatar);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        KLog.i("Evd", "call - throwable");
                    }
                });

        isPrepared = true;
        lazyLoad();
        return view;
    }

    @OnClick(R.id.relative_me_person)
    public void relative_me_person(View view) {
        startActivity(new Intent(getActivity(), PersonActivity.class));
    }

//    @OnClick(R.id.relative_me_money)
//    public void relative_me_money(View view) {
//        startActivity(new Intent(getActivity(), AccountingActivity.class));
//    }

    @OnClick(R.id.relative_me_password)
    public void relative_me_password(View view) {
        startActivity(new Intent(getActivity(), UpPasswordActivity.class));
    }

    @OnClick(R.id.relative_me_ti_xian)
    public void relative_me_ti_xian(View view) {
        startActivity(new Intent(getActivity(), FillInActivity.class));

    }

    @OnClick(R.id.relative_me_about)
    public void relative_me_about(View view) {
        startActivity(new Intent(getActivity(), PublicWebView.class).putExtra("id_url", url).putExtra("id_title", R.string.str_me_about));
    }

    @Override
    public Context getContext() {
        return getActivity();
    }


    Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    long progress = (long) msg.obj;
                    numberProgressBar.incrementProgressBy((int) (progress / 1000 % 1000));
                    break;
            }
        }
    };

    @Override
    public void updateProgress(final long numberProgress) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Message msg = new Message();
                    msg.what = 100;
                    msg.obj = numberProgress;
                    myHandler.sendMessage(msg);
                } catch (Exception e) {

                }

            }
        }).start();
    }

    @Override
    public void installationApk(File file) {
        updateProgressBarDialog.dismiss();
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);


    }

    @Override
    public void noUpdatesVersionCode(String message) {
        EasyToast.showShort(getActivity(), message);
    }

    class UpdateCancelDetermineListener implements View.OnClickListener {
        String versionName;
        String apkUrl;

        UpdateCancelDetermineListener(final String versionName, final String apkUrl) {
            this.versionName = versionName;
            this.apkUrl = apkUrl;
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.tv_cancel:
                    updateProgressBarDialog.dismiss();
                    break;
                case R.id.tv_determine:
                    /**
                     * @see HomeMainPresenter#downloadApk(String, String)
                     */
                    homeMainActionsListener.downloadApk(versionName, apkUrl, numberProgressBar);
                    break;
                default:
                    break;
            }
        }
    }


    class UpdateProgressBarDialog extends Dialog {
        UpdateCancelDetermineListener listener;

        public void setListener(UpdateCancelDetermineListener listener) {
            this.listener = listener;
        }

        public UpdateProgressBarDialog(Context context, boolean cancelable,
                                       OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
            // TODO Auto-generated constructor stub
        }

        public UpdateProgressBarDialog(Context context, int theme) {
            super(context, theme);
            // TODO Auto-generated constructor stub
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            View view = getLayoutInflater().inflate(R.layout.update_app_progress_bar_dialog, null);
            numberProgressBar = (NumberProgressBar) view.findViewById(R.id.numberbar1);
            tv_dialog_version = (TextView) view.findViewById(R.id.tv_dialog_version);
            setContentView(view);
            initDialogSize();
            view.findViewById(R.id.tv_cancel).setOnClickListener(listener);
            view.findViewById(R.id.tv_determine).setOnClickListener(listener);

        }

        private void initDialogSize() {
            // TODO Auto-generated method stub
            Window dialogWindow = this.getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setGravity(Gravity.CENTER);
            lp.width = displayWidth - 60;
            lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            dialogWindow.setAttributes(lp);
        }
    }


    @Override
    public void showDialog(final String versionName, final String apkUrl) {
        updateProgressBarDialog = new UpdateProgressBarDialog(getActivity(), R.style.progress_bar_style);
        updateProgressBarDialog.setListener(new UpdateCancelDetermineListener(versionName, apkUrl));
        updateProgressBarDialog.show();
        updateProgressBarDialog.setCanceledOnTouchOutside(false);
        tv_dialog_version.setText("有最新版本：" + versionName);
    }

    @OnClick(R.id.relative_me_version)
    public void relative_me_version(View view) {
        versionCode = (String) SPUtil.get(getActivity(), "version_code", "1");
        versionName = (String) SPUtil.get(getActivity(), "version_name", "1.0");
        /**
         * @see HomeMainPresenter#isDownloadApk(String, String)
         */
        homeMainActionsListener.isDownloadApk(versionCode, versionName, true);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);//解除绑定，官方文档只对fragment做了解绑
    }
}
